use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::customer_favorites::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub customer_id: String,
    pub product_id: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Customer ID must not be empty."))]
    pub customer_id: String,
    #[validate(length(min = 1, message = "Product ID must not be empty."))]
    pub product_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            customer_id: self.customer_id.as_ref().to_owned(),
            product_id: self.product_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::customer_favorites::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a customer favorite by the provided id
    ///
    /// # Errors
    ///
    /// When could not find customer favorite or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let customer_favorite = customer_favorites::Entity::find()
            .filter(
                model::query::condition()
                    .eq(customer_favorites::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        customer_favorite.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds customer favorites by the provided customer id
    ///
    /// # Errors
    ///
    /// When could not find customer favorites or DB query error
    pub async fn find_by_customer_id(
        db: &DatabaseConnection,
        customer_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let customer_favorites = customer_favorites::Entity::find()
            .filter(
                model::query::condition()
                    .eq(customer_favorites::Column::CustomerId, customer_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(customer_favorites)
    }

    /// finds customer favorite by the provided customer id and product id
    ///
    /// # Errors
    ///
    /// When could not find customer favorite or DB query error
    pub async fn find_by_customer_and_product(
        db: &DatabaseConnection,
        customer_id: &str,
        product_id: &str,
    ) -> ModelResult<Self> {
        let customer_favorite = customer_favorites::Entity::find()
            .filter(
                model::query::condition()
                    .eq(customer_favorites::Column::CustomerId, customer_id)
                    .eq(customer_favorites::Column::ProductId, product_id)
                    .build(),
            )
            .one(db)
            .await?;
        customer_favorite.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// Asynchronously creates a customer favorite and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the customer favorite into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        if customer_favorites::Entity::find()
            .filter(
                model::query::condition()
                    .eq(customer_favorites::Column::CustomerId, &params.customer_id)
                    .eq(customer_favorites::Column::ProductId, &params.product_id)
                    .build(),
            )
            .one(&txn)
            .await?
            .is_some()
        {
            return Err(ModelError::EntityAlreadyExists {});
        }

        let customer_favorite = customer_favorites::ActiveModel {
            customer_id: ActiveValue::set(params.customer_id.to_string()),
            product_id: ActiveValue::set(params.product_id.to_string()),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(customer_favorite)
    }

    /// Deletes the customer favorite from the database
    ///
    /// # Errors
    ///
    /// When could not delete the customer favorite from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: customer_favorites::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}
